/*
 * Copyright (C) 2010,  Tomislav Milkovic
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 */
package hr.ws4is.websocket;

import hr.ws4is.JsonDecoder;
import hr.ws4is.websocket.data.WebSocketRequest;

import javax.enterprise.inject.Vetoed;
import javax.websocket.DecodeException;
import javax.websocket.Decoder;
import javax.websocket.EndpointConfig;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Internal JSON decoder for WebSocket ExtJS request
 *
 */
@Vetoed
public class WebsocketDecoder implements Decoder.Text<WebSocketRequest> {

    private static final Logger LOGGER = LoggerFactory.getLogger(WebsocketDecoder.class);

    @Override
    public final WebSocketRequest decode(final String message) throws DecodeException {

        WebSocketRequest wsMessage = null;

        try {
            final JsonDecoder<WebSocketRequest> jd = new JsonDecoder<>(WebSocketRequest.class, message);
            wsMessage = jd.getObject();
        } catch (Exception exception) {
            LOGGER.error(exception.getMessage(), exception);
            throw new DecodeException(message, exception.getMessage(), exception);
        }
        return wsMessage;
    }

    @Override
    public final boolean willDecode(final String message) {
        boolean decode = false;
        if (message != null) {
            decode = message.trim().startsWith("{") && message.trim().endsWith("}");
        }
        return decode;
    }

    @Override
    public void destroy() {

    }

    @Override
    public void init(final EndpointConfig arg0) {

    }

}
